
using System.Collections.Generic;
using System.Xml;
using UserInterface.Misc;

namespace UserInterface.MML.Base
{
    public interface ITextFilter
    {
        string Filter(string text);
    }
    
    public static class TextFilterManager
    {
        private static List<ITextFilter> filters = new List<ITextFilter>();

        public static void RegisterFilter(ITextFilter filter)
        {
            filters.Add(filter);
        }

        public static string Filter(string text)
        {
            foreach (ITextFilter filter in filters)
            {
                text = filter.Filter(text);
            }
            return text;
        }
    }

    public class NewLineToBreakTextFilter : ITextFilter
    {
        public string Filter(string text)
        {
            return OutputTools.ConvertNewLinesToBreaks(text);
        }
    }

    public class HTMLEntitiesTextFilter : ITextFilter
    {
        public string Filter(string text)
        {
            return OutputTools.HTMLEntities(text);
        }
    }

    public class EmoticonTextFilter : ITextFilter
    {
        private const string EmoticonsFileBasePath = "./Emoticons";

        private class EmoticonReplacement
        {
            public string Code;
            public string Replacement;

            public EmoticonReplacement(string code, string name, string image)
            {
                Code = code;
                Replacement = "<img src=\"" + EmoticonsFileBasePath + "/" + image + "\" alt=\"" + name + "\" />";
            }
        }

        private List<EmoticonReplacement> emoticonReplacements = new List<EmoticonReplacement>();

        public EmoticonTextFilter(string emoticonsFile)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(emoticonsFile);
            foreach (XmlElement emoticonElement in doc.SelectNodes("/emoticons/emoticon"))
            {
                string code = emoticonElement["code"].InnerText;
                string name = emoticonElement["name"].InnerText;
                string image = emoticonElement["image"].InnerText;
                emoticonReplacements.Add(new EmoticonReplacement(code, name, image));
            }
        }

        public string Filter(string text)
        {
            foreach (EmoticonReplacement replacement in emoticonReplacements)
            {
                text = text.Replace(replacement.Code, replacement.Replacement);
            }
            return text;
        }
    }
}